<?php

namespace app\command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Output\OutputInterface;
use think\facade\Db;


class ConfigMysql extends Command
{
    protected static $defaultName = 'config:mysql';
    protected static $defaultDescription = 'config mysql';

    /**
     * @return void
     */
    protected function configure()
    {
        $this->addArgument('name', InputArgument::OPTIONAL, 'Name description');
    }


    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $sqlPath = base_path() . '/app/command/install.sql';

        if (!file_exists($sqlPath)) {
            $output->writeln("<error>SQL 文件不存在: {$sqlPath}</error>");
            return self::FAILURE;
        }

        $output->writeln("<info>开始执行 SQL 文件: {$sqlPath}</info>");

        $sqlContent = file_get_contents($sqlPath);

        // 多语句分割（去除注释和空语句）
        $sqlStatements = array_filter(array_map('trim', explode(';', $sqlContent)));

        foreach ($sqlStatements as $index => $statement) {
            if (!empty($statement)) {
                try {
                    Db::execute($statement);
                    $output->writeln("<info>[OK] 执行第 " . ($index + 1) . " 条 SQL 成功</info>");
                } catch (\Exception $e) {
                    $output->writeln("<error>[ERROR] 第 " . ($index + 1) . " 条 SQL 失败: " . $e->getMessage() . "</error>");
                }
            }
        }

        $output->writeln("<info>✅ SQL 文件执行完成</info>");
        return self::SUCCESS;
    }

}
